package com.easyto.filter;

import com.easyto.predicate.CustomRoutePredicateFactory;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 开头任意取名，但是必须以GatewayFilterFactory后缀结尾 <br/>
 *
 * yaml配置过滤器：
 * filters:
 *      - CustomSingle=youxiao
 * CustomSingle指定CustomSingleGatewayFilterFactory断言工厂
 * youxiao则是指定{@link Config}中status的值。
 * 表示请求路径中包含请求参数为youxiao时，则通过请求
 * http://localhost:9090/click-ppc/test/11/chain/2222/details?userLevel=gold&youxiao=statssss
 * @Description 自定义filters
 */

@Slf4j
@Component
public class CustomSingleGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomSingleGatewayFilterFactory.Config> {

    /**
     * 表示过滤器要接收到一个什么类型的参数才能正常运行
     */
    public CustomSingleGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            log.info("进入单一的过滤器 status: {}", config.getStatus());
            ServerHttpRequest request = exchange.getRequest();
            if (request.getQueryParams().containsKey(config.getStatus())) {
                return chain.filter(exchange);
            }
            exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
            return exchange.getResponse().setComplete();
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("status");
    }

    @Getter
    @Setter
    public static class Config {
        private String status;
    }

}

